<?php
/**
 * Created by PhpStorm.
 * User: wx:wenyi2048
 * Date: 2022/3/19 0019
 * Time: 14:09
 */
namespace app\common\service;

use app\common\model\AdminUser;
use think\Exception;
use think\Session;
use think\Db;

class StoreService extends Service
{
    protected $tableName = 'sms_mk_stores';

    public function searchPage(&$view,$params,$isdelete = 0){

        $this->db->where('isdelete','=',$isdelete)
            ->order('id','desc')
            ->field('*');
        if(@$params['number']) $this->db->where('number','like','%'.$params['number'].'%');
        if(@$params['name']) $this->db->where('name','like','%'.$params['name'].'%');
        if(@$params['phone']) $this->db->where('phone','like','%'.$params['phone'].'%');
        if(@$params['types_third_id']) $this->db->where('types_third_id','=',$params['types_third_id']);

        $this->pageList($view,$params);
    }

//    public function getStore($userId=0){
//        if(Session::get('auth_id')!=3)//判断，管理员可以随便选择，不是管理员只能查看自己店铺
//            $userId = Session::get('auth_id');
//        $this->db->where('id','=',$userId);
//        return $this->db->value('*');
//    }

    /**
     * 用于api直接添加店铺
     */
    public function apiAdd()
    {
        $param = $this->param;
        $param['id'] = parent::add(); // TODO: Change the autogenerated stub
        return $this->overAdd($param);
    }


    public function overAdd($params){
        $storeId = $params['id'];
        //添加店铺管理员
        $user = new AdminUser();
        $user->realname = $params['name'];
        $user->account = $params['phone'];
        $user->mobile = $params['phone'];
        $user->password = password_hash_tp($params['phone']);
        $user->email = $params['email'];
        $user->status = 1;
        $user->save();

        if($params['province']){
            $point = $this->getLngLat($params['province'],$params['province'].@$params['city'].@$params['area'].@$params['detailed_address']);
        }
        $sno='S'.date('Ymd').sprintf("%07d", $storeId);
        $data = [
            'number'=>$sno,
            'admin_id'=>$user['id'],
            'lng'=>@$point[0],
            'lat'=>@$point[1]
        ];
        Db::table('sms_mk_stores')->where('id','=',$storeId)
            ->update($data);

        //添加权限   1商铺， 2超管
        return Db::table('sms_admin_role_user')->insert(['role_id'=>1,'user_id'=>$user['id']]);
        //$user->setPasswordAttr($params['phone']);
    }

    public function getLngLat($province,$address){
        //获取店铺经纬度
        $url = "https://restapi.amap.com/v3/geocode/geo";
        // 参数
        $url .= '?key='.config('amap')['key'];;
        $url .='&address='.$address;//$params['province'].$params['city'].$params['area'].$params['detailed_address'];
        $url .='&city='.$province;//$params['province'];
        $arr = file_get_contents($url);
        $arr = json_decode($arr,true);
        $point = [];
        if(@$arr['geocodes'][0]['location'])
            $point = explode(',',$arr['geocodes'][0]['location']);
        return $point;
    }


    public function businessSave($params){
        $data = array();
        if(ADMINISTRATOR)
            if(!empty($params['phone'])) $data['phone'] = $params['phone'];

        if(!empty($params['name'])) $data['name'] = $params['name'];
        if(!empty($params['thumb']) && $params['thumb']) $data['thumb'] = join(',',$params['thumb']);
        if(!empty($params['province'])) $data['province'] = $params['province'];
        if(!empty($params['city'])) $data['city'] = $params['city'];
        if(!empty($params['area'])) $data['area'] = $params['area'];
        if(!empty($params['detailed_address'])) $data['detailed_address'] = $params['detailed_address'];

        if(@$params['province'])
            $point = $this->getLngLat($params['province'],$params['province'].@$params['city'].@$params['area'].@$params['detailed_address']);
        if(@$point){
            $data['lng'] = @$point[0];
            $data['lat'] = @$point[1];
        }

        if(!empty($params['engage_in'])) $data['engage_in'] = $params['engage_in'];
        if(!empty($params['tag'])) $data['tag'] = $params['tag'];
        if(!empty($params['intro'])) $data['intro'] = $params['intro'];
        try {
            //管理员操作检测
            $storeId = $this->checkStoreSelect(@$params['store_id']);
            return $this->db->where('id','=',$storeId)->update($data);
        }catch (Exception $e){
            apiError($e->getMessage());
        }

    }

//    public function getSelectStore($storeId){
//        $storeId = $this->checkStoreSelect($storeId);
//        return $this->db->where('id','=',$storeId)->find();
//    }


    /**
     * @return array
     * 以下三个直接从以前的商品收藏改的，只是添加了一个一样的新表，其他逻辑不改
     */

    public function getGoodsStar(){
        $this->setDb('store_goods_view');
        $stars = Db::table('sms_mk_stores_star')
            ->where('sms_users_id','=',$this->param['sms_users_id'])
            ->column('sms_goods_id');
        $result = array();
        if($stars){
            $this->db->whereIn('store_id',$stars);
            $result = parent::datalist();
            //->select();
        }
        return $result;
    }

    public function getGoodsStarId(){
        return Db::table('sms_mk_stores_star')
            ->where('sms_users_id','=',$this->param['sms_users_id'])
            ->where('sms_goods_id','=',$this->param['goods_id'])
            ->find();
    }


    public function delGoodsStar(){
        $ids = $this->param['store_id'];
        if(!is_array($ids)) $ids = [$ids];
        return Db::table('sms_mk_stores_star')
            ->where('sms_users_id','=',$this->param['sms_users_id'])
            ->whereIn('sms_goods_id',$ids)
            ->delete();
    }

    public function setGoodsStar(){
        $ids = $this->param['store_id'];
        if(!is_array($ids)) $ids = [$ids];
        $inData = [];
        foreach ($ids as $id){
            $inData[] = [
                'sms_users_id'=>$this->param['sms_users_id'],
                'sms_goods_id'=>$id
            ];
        }
        return Db::table('sms_mk_stores_star')->insertAll($inData);
    }
}